package com.lx.work2;

import java.io.*;
import java.util.List;

/**
 * @author c先生
 * @date 2022年04月06日 下午 7:36:39
 * @describe
 */

public class UserManager {

    //注册用户
    public boolean regUser(List<User> users) {
        //序列化
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("E:/Users/c先生/Desktop/user.txt"));
            oos.writeObject(users);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public List<User> findAllUser(){
        //反序列化
        File file = new File("E:/Users/c先生/Desktop/user.txt");
        List<User> userList = null;
        ObjectInputStream ois = null;
        if (file.exists()) {//如果该文件存在
            FileInputStream fileIntputStream = null;
            try {
                fileIntputStream = new FileInputStream(file);
                ois = new ObjectInputStream(fileIntputStream);
                userList = (List<User>) ois.readObject();//反序列化读取
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }finally {
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return userList;
        } else {//如果该文件不存在
            String absolutePath = file.getAbsolutePath();
            String path = absolutePath.substring(0, absolutePath.lastIndexOf("\\"));
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdir();//创建目录
            }
            try {
                file.createNewFile();//创建user.txt文件
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
